package com.heima.app.filter;

import com.heima.app.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 鉴权过滤器
 * @author Mr.Chen
 */
@Component
public class AuthorFilter2 implements GlobalFilter,Ordered{
    /**
     * 过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.通过请求路径判断是否是登录请求，如果是，则放行，否则拦截
        //2.1获取请求路径地址
        URI uri = request.getURI();
        System.out.println(uri);
        String path = request.getURI().getPath();
        System.out.println(path);
        //2.2 判断是否是登录请求
        if(path.contains("/login/login_auth")){
            return chain.filter(exchange );
        }
//否则就不是登录请求，那么要拦截

        //2.4 从请求头中获取token
        String jwtToken = request.getHeaders().getFirst("token");
        //2.5 判断当前token是否为空
        if(StringUtils.isEmpty(jwtToken)){
            //设置状态码401，表示没有认证权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //响应给401到浏览器上完成
            return response.setComplete();
        }

        //2.6判断token是否有效
            //2.6.1 解析token的内容
        Claims claimsBody = AppJwtUtil.getClaimsBody(jwtToken);
        if(claimsBody==null){
            //设置状态码401，表示没有认证权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //响应给401到浏览器上完成
            return response.setComplete();
        }
            //2.6.2 验证token是否过期
        int i = AppJwtUtil.verifyToken(claimsBody);
        if(i==1 ||i==2){
            //设置状态码401，表示没有认证权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //响应给401到浏览器上完成
            return response.setComplete();
        }
        if(i==-1  || i==0){
            //从cliams中获取用户id
            int id = (int) claimsBody.get("id");
            //把id再次封装到请求头中
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", id + "");
            }).build();

            exchange.mutate().request(serverHttpRequest).build();
        }

        //放行
        return chain.filter(exchange);
    }

    /**
     * 执行优先级，返回值越小，优先级越高
     * @return 返回值
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
